package com.garbagecode.resultbounds;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;

/**
 * 
 * 这个类干嘛用的，请参考 PaginationInterceptor.intercept 方法
 *
 */
public class TotalCount extends RowBounds {
  private String statement;
  private Object parameter;
  private Long total;

  public TotalCount(String statement, Object parameter) {
    this.statement = statement;
    this.parameter = parameter;
    this.total = null;
  }
  
  /**
   * 返回符合查询条件的记录总数
   * @param sqlSession
   * @return
   */
  public long getTotal(SqlSession sqlSession) {
    if (sqlSession == null) {
      throw new IllegalArgumentException("sqlSession null");
    }

    if (statement == null) {
      throw new RuntimeException("property 'statement' is null");
    }

    if (total != null) {
      return total;
    }

    List<Long> lt = sqlSession.selectList(statement, parameter, this);

    if (lt.size() <= 0) {
      throw new RuntimeException("none result");
    }

    total = lt.get(0);
    return total;
  }
  
}
